package com.xzst.jacksonxml.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import java.io.IOException;
import java.util.Map;


/**
 * @ClassName: XmlUtil
 * @Author: LiuKeXin
 * @Date: Create in 2019-03-26 15:36
 */
public class XmlUtil {
    /**
     * ObjectMapper是JSON操作的核心，Jackson的所有JSON操作都是在ObjectMapper中实现。
     * ObjectMapper有多个JSON序列化的方法，可以把JSON字符串保存File、OutputStream等不同的介质中。
     * writeValue(File arg0, Object arg1)把arg1转成json序列，并保存到arg0文件中。
     * writeValue(OutputStream arg0, Object arg1)把arg1转成json序列，并保存到arg0输出流中。
     * writeValueAsBytes(Object arg0)把arg0转成json序列，并把结果输出成字节数组。
     * writeValueAsString(Object arg0)把arg0转成json序列，并把结果输出成字符串。
     */
    private final static ObjectMapper objectMapper = new ObjectMapper();

    private final static XmlMapper xmlMapper = new XmlMapper();

    static {
        xmlMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
        //设置为true时，属性名称不带双引号
        xmlMapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, true);
        xmlMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        xmlMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        xmlMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
        //null的属性不序列化
        xmlMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //按字母顺序排序属性,默认false
        xmlMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
        //xml格式化
        xmlMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
        //忽略pojo中不存在的字段
        xmlMapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, true);
        //设置转换模式
        xmlMapper.enable(MapperFeature.USE_STD_BEAN_NAMING);
    }

    public static String beanToJson(Object o) throws JsonProcessingException {
        return objectMapper.writeValueAsString(o);
    }

    public static <T> T jsonToBean(String json, Class<T> valueType) throws IOException {
        return objectMapper.readValue(json, valueType);
    }

    public static String beanToXml(Object o) throws JsonProcessingException {
        return new String("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + xmlMapper.writeValueAsString(o));
    }

    public static <T> T xmlToBean(String xmlData, Class<T> valueType) throws IOException {
        return xmlMapper.readValue(xmlData, valueType);
    }

    public static Map<String, Object> jsonToMap(String json) throws IOException {
        return objectMapper.readValue(json, Map.class);
    }

}